package com.zzyl.nursing.service.impl;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 * 
 * @author alexis
 * @date 2025-09-13
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;


    @Value("${token.secret}")
    private String secret;
    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return familyMemberMapper.selectById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.insert(familyMember);
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.updateById(familyMember);
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return familyMemberMapper.deleteById(id);
    }

    /**
     * 微信小程序登录
     * @param userLoginRequestDto   登录参数
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //1.获取openid
        String openid = wechatService.getOpenid(userLoginRequestDto.getCode());
        //2.根据openid查询用户信息
        LambdaQueryWrapper<FamilyMember> qw = new LambdaQueryWrapper<>();
        qw.eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = familyMemberMapper.selectOne(qw);
        //2.2 如果为空，则需要创建新的用户信息，并赋值openid
        if (familyMember == null) {
            familyMember = new FamilyMember();
            familyMember.setOpenId(openid);
        }
        //3.获取手机号
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());
        familyMember.setPhone(phone);
        //4.新增或更新用户信息
        if (familyMember.getId() == null){
            //新增
            familyMember.setName(generateRandomName());
            familyMemberMapper.insert(familyMember);
        }else {
            //更新
            familyMemberMapper.updateById(familyMember);
        }
        //5.生成JWT并返回
        Map<String, Object> claims = new HashMap<>();
        //用户id
        claims.put("userId", familyMember.getId());
        //用户昵称
        claims.put("nickName", familyMember.getName());
        String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512,secret).compact();

        return LoginVo.builder()
                .token(token)
                .nickName(familyMember.getName())
                .build();
    }

    /**
     * 生成随机名称
     * @return 随机名称
     */
    private String generateRandomName() {
        String[] prefixes = {"用户", "家属", "客户", "会员", "访客"};
        String[] suffixes = {"一号", "二号", "三号", "四号", "五号",
                "A", "B", "C", "D", "E",
                String.valueOf(System.currentTimeMillis() % 10000),
                String.valueOf(Math.abs(new Random().nextInt()) % 10000)};

        Random random = new Random();
        String prefix = prefixes[random.nextInt(prefixes.length)];
        String suffix = suffixes[random.nextInt(suffixes.length)];

        return prefix + suffix;
    }
}
